<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" :model="formData">
      <a-row>
        <a-col :span="24">
          <a-form-item label="小说ID" v-bind="validateInfos.bookId">
            <a-input v-model:value="formData.bookId" placeholder="请输入小说ID" @blur="getBookNameById" style="width: 100%" />
            <div class="error-tip" v-if="findFailedTip">找不到该小说！</div>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="小说名称" v-bind="validateInfos.bookName">
            <a-input v-model:value="formData.bookName" placeholder="" style="width: 100%" disabled />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="起始目录号" v-bind="validateInfos.startNum">
            <a-input-number
              v-model:value="formData.startNum"
              :min="0"
              placeholder="请输入起始目录号"
              style="width: 100%"
              :precision="0"
              @blur="
                (data) => {
                  getCatalogNameById(data, 'start');
                }
              "
            />
            <div v-if="startCataLogName">目录名：{{ startCataLogName }}</div>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="截止目录号" v-bind="validateInfos.endNum">
            <a-input-number
              v-model:value="formData.endNum"
              :min="0"
              placeholder="请输入截止目录号"
              style="width: 100%"
              :precision="0"
              @blur="
                (data) => {
                  getCatalogNameById(data, 'end');
                }
              "
            />
            <div v-if="endCataLogName">目录名：{{ endCataLogName }}</div>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否收费" v-bind="validateInfos.isVip">
            <a-select v-model:value="formData.isVip">
              <a-select-option :value="false">免费</a-select-option>
              <a-select-option :value="true">收费</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="章节费用" v-bind="validateInfos.bookPrice">
            <a-input-number :min="0" :precision="0" v-model:value="formData.bookPrice" placeholder="请输入章节费用" style="width: 100%" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JSwitch from '/@/components/Form/src/jeecg/components/JSwitch.vue';
  import { getValueType } from '/@/utils';
  import { getBookName, getCatalogName, batchSetChapterPrice } from '../BookIndex.api';
  import { Form } from 'ant-design-vue';
  import type { Rule } from 'ant-design-vue/es/form';
  import setting from '/@/settings/projectSetting';

  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => {} },
    formBpm: { type: Boolean, default: true },
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    bookId: undefined,
    bookName: undefined,
    startNum: undefined,
    endNum: '',
    isVip: true,
    bookPrice: 10,
  });
  const validStartNumber = async (_rule: Rule, value: string) => {
    if (value === '') {
      return Promise.reject('请输入起始目录号!');
    } else {
      if (formData.endNum && value > formData.endNum) {
        return Promise.reject('起始目录号需小于截止目录号!');
      } else {
        return Promise.resolve();
      }
    }
  };
  const validEndNumber = async (_rule: Rule, value: string) => {
    if (value === '') {
      return Promise.resolve();
    } else {
      if (value < formData.startNum) {
        return Promise.reject('截止目录号需大于起始目录号!');
      } else {
        return Promise.resolve();
      }
    }
  };
  const findFailedTip = ref<Boolean>(false);
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = {
    bookId: [{ required: true, message: '请输入小说ID!' }],
    bookName: [{ required: true, message: '小说名称不能为空!' }],
    startNum: [{ validator: validStartNumber, trigger: 'change' }],
    endNum: [{ validator: validEndNumber, trigger: 'change' }],
    isVip: [{ required: true, message: '请选择是否收费!' }],
    bookPrice: [{ required: true, message: '请输入章节费用!' }],
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: true });
  const startCataLogName = ref<string>('');
  const endCataLogName = ref<string>('');

  /**
   * 设置
   */
  function set() {
    nextTick(() => {
      resetFields();
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    confirmLoading.value = true;
    //时间格式化
    let model = formData;
    await batchSetChapterPrice(model)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          findFailedTip.value = false;
          startCataLogName.value = '';
          endCataLogName.value = '';
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  function cancelForm() {
    resetFields();
    findFailedTip.value = false;
    startCataLogName.value = '';
    endCataLogName.value = '';
  }

  // 输入框失焦获取书名
  async function getBookNameById(e) {
    if (e.target.value) {
      const reg = /^[0-9]*$/;
      if (!reg.test(e.target.value)) {
        createMessage.warning('格式错误，请重新输入！');
      } else {
        await getBookName({ bookId: e.target.value })
          .then((res) => {
            if (res.success) {
              if (res.result) {
                formData.bookName = res.result.bookName;
                findFailedTip.value = false;
              } else {
                findFailedTip.value = true;
                formData.bookName = '';
              }
            } else {
              createMessage.warning(res.message);
              findFailedTip.value = true;
              formData.bookName = '';
            }
          })
          .finally(() => {});
      }
    } else {
      findFailedTip.value = false;
      formData.bookName = undefined;
    }
  }

  // 输入框失焦获取目录名
  async function getCatalogNameById(e, type) {
    setTimeout(async () => {
      if (e.target.value) {
        await validate();
        // formRef.value.validateFields(['startNum']);
        // formRef.value.validateFields(['endNum']);
        if (formData.bookId) {
          await getCatalogName({ indexNum: e.target.value, bookId: formData.bookId })
            .then((res) => {
              if (res.success) {
                type === 'start' ? (startCataLogName.value = res.result) : (endCataLogName.value = res.result);
              } else {
                createMessage.warning(res.message);
                type === 'start' ? (startCataLogName.value = '') : (endCataLogName.value = '');
              }
            })
            .finally(() => {});
        } else {
          type === 'start' ? (formData.startNum = '') : (formData.endNum = '');
          createMessage.warning('请输入小说ID！');
        }
      } else {
        type === 'start' ? (startCataLogName.value = '') : (endCataLogName.value = '');
      }
    }, 100);
  }

  defineExpose({
    set,
    submitForm,
    cancelForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    min-height: 500px !important;
    overflow-y: auto;
    padding: 24px 24px 24px 24px;
  }
  .error-tip {
    color: #ed6f6f;
  }
</style>
